/**
 * Background Script 事件处理器
 * 处理扩展的各种事件监听
 */

import { StorageService } from "./services/StorageService";
import { TabService } from "./services/TabService";
import { ConfigManager } from "./services/ConfigService";
import { TabInfo, MessageType, CountElementsResponse, type StorageChangedNotification } from "@utils/types";
import { CONTENT_SCRIPT_MATCHES, STORAGE_KEYS, LOGGER_CONFIG, DEBUG } from "@utils/constants";
import { MessageSender } from "@utils/messaging";

/**
 * 初始化所有事件监听器
 */
export function initializeEventHandlers(
  storageService: StorageService,
  tabService: TabService,
  configManager: ConfigManager
) {
  // 扩展安装和更新事件
  setupExtensionEvents(configManager, tabService);

  // 标签页事件
  setupTabEvents(tabService);

  // 存储事件
  setupStorageEvents(storageService, tabService);

  // 其他浏览器事件
  setupBrowserEvents();
}

/**
 * 扩展安装和更新事件处理
 */
function setupExtensionEvents(configManager: ConfigManager, tabService: TabService) {
  browser.runtime.onInstalled.addListener(async (details) => {
    console.log("📦 Extension event:", details.reason);

    try {
      switch (details.reason) {
        case "install":
          await handleFirstInstall(configManager, tabService);
          break;

        case "update":
          await handleUpdate(details.previousVersion!, configManager);
          break;

        case "chrome_update":
        case "shared_module_update":
          console.log("🔄 Browser or shared module updated");
          break;
      }
    } catch (error) {
      console.error("Error handling extension event:", error);
    }
  });
}

/**
 * 处理首次安装
 */
async function handleFirstInstall(configManager: ConfigManager, tabService: TabService) {
  console.log("✨ Welcome! Extension installed for the first time.");

  // 初始化默认配置
  await configManager.getConfig(); // 这会创建默认配置

  // 可以打开欢迎页面
  // await tabService.createTab({
  //   url: browser.runtime.getURL('/welcome.html'),
  //   active: true
  // });

  // 显示安装成功通知
  if (browser.notifications) {
    try {
      await browser.notifications.create({
        type: "basic",
        iconUrl: "/icon/48.png",
        title: "扩展安装成功！",
        message: "感谢使用我们的浏览器扩展，点击扩展图标开始使用。",
      });
    } catch (error) {
      console.warn("Failed to show installation notification:", error);
    }
  }
}

/**
 * 处理扩展更新
 */
async function handleUpdate(previousVersion: string, configManager: ConfigManager) {
  console.log(`🔄 Extension updated from version: ${previousVersion}`);

  const currentConfig = await configManager.getConfig();

  // 根据版本进行配置迁移
  if (needsConfigMigration(previousVersion, currentConfig.version)) {
    await migrateConfig(previousVersion, configManager);
  }

  // 显示更新通知
  if (browser.notifications) {
    try {
      await browser.notifications.create({
        type: "basic",
        iconUrl: "/icon/48.png",
        title: "扩展已更新！",
        message: `扩展已从 ${previousVersion} 更新到 ${currentConfig.version}`,
      });
    } catch (error) {
      console.warn("Failed to show update notification:", error);
    }
  }
}

/**
 * 检查是否需要配置迁移
 */
function needsConfigMigration(previousVersion: string, currentVersion: string): boolean {
  // 这里可以添加版本比较逻辑
  const prev = parseVersion(previousVersion);
  const curr = parseVersion(currentVersion);

  return curr.major > prev.major || curr.minor > prev.minor;
}

/**
 * 配置迁移
 */
async function migrateConfig(previousVersion: string, configManager: ConfigManager) {
  console.log(`🔧 Migrating config from ${previousVersion}`);

  // 这里可以添加具体的配置迁移逻辑
  // 例如：添加新的配置项、删除废弃的配置项等

  const currentConfig = await configManager.getConfig();

  // 示例迁移逻辑
  if (parseVersion(previousVersion).major < 1) {
    // 从 0.x 版本升级到 1.x 版本的迁移
    await configManager.updateConfig({
      ...currentConfig,
      // 添加新的配置项
      enabledFeatures: [...(currentConfig.enabledFeatures || []), "new-feature"],
      // 更新版本号
      version: "1.0.0",
    });
    console.log("✅ Configuration migrated to v1.0.0");
  }
}

/**
 * 解析版本号
 */
function parseVersion(version: string): { major: number; minor: number; patch: number } {
  const [major = "0", minor = "0", patch = "0"] = version.split(".");
  return {
    major: parseInt(major, 10),
    minor: parseInt(minor, 10),
    patch: parseInt(patch, 10),
  };
}

/**
 * 标签页事件处理
 */
function setupTabEvents(tabService: TabService) {
  tabService.onTabUpdated((tabId, changeInfo, tabInfo) => {
    if (changeInfo.status === "complete" && tabInfo.url) {
      console.log("📄 Tab loaded:", {
        tabId,
        url: tabInfo.url,
        title: tabInfo.title,
      });

      // 可以在这里执行页面分析、统计等
      handlePageLoad(tabId, tabInfo);
    }
  });

  tabService.onTabCreated((tabInfo) => {
    console.log("🆕 New tab created:", {
      tabId: tabInfo.id,
      url: tabInfo.url,
    });
  });
}

/**
 * 处理页面加载完成事件
 */
async function handlePageLoad(tabId: number, tabInfo: TabInfo) {
  try {
    // 检查是否是受支持的页面
    if (!tabInfo.url || !isSupportedUrl(tabInfo.url)) {
      return;
    }

    // 可以在这里执行一些自动操作
    // 例如：自动注入某些样式、收集页面信息等

    // 收集页面统计信息
    await collectPageStats(tabId, tabInfo);

    if (DEBUG) {
      console.log(`✅ Page analysis completed for tab ${tabId}`);
    }
  } catch (error) {
    console.error("Error handling page load:", error);
  }
}

/**
 * 收集页面统计信息
 */
async function collectPageStats(tabId: number, tabInfo: TabInfo) {
  try {
    // 发送消息给 content script 收集页面统计
    const stats = await MessageSender.sendToContent(tabId, {
      type: MessageType.COUNT_ELEMENTS,
      selector: "a, img, video, form",
    });

    if (stats.success && DEBUG) {
      console.log(`📊 Page stats for ${tabInfo.url}:`, {
        elements: (stats as CountElementsResponse).count,
        title: tabInfo.title,
      });
    }
  } catch (error) {
    // 忽略无法发送消息的页面（如系统页面）
    console.debug("Could not collect stats for tab:", tabId);
  }
}

/**
 * 检查是否是受支持的URL
 */
function isSupportedUrl(url: string): boolean {
  return CONTENT_SCRIPT_MATCHES.some((pattern) => {
    const regex = new RegExp(pattern.replace(/\*/g, ".*"));
    return regex.test(url);
  });
}

/**
 * 存储事件处理
 */
function setupStorageEvents(storageService: StorageService, tabService: TabService) {
  storageService.onStorageChanged((changes) => {
    if (LOGGER_CONFIG.enabled) {
      const changedKeys = Object.keys(changes);
      console.log("💾 Storage changed:", {
        keys: changedKeys,
        count: changedKeys.length,
      });
    }

    // 广播给可注入且受支持的标签页，避免无效发送
    (async () => {
      const payload: StorageChangedNotification = {
        type: MessageType.STORAGE_CHANGED,
        changes: Object.fromEntries(
          Object.entries(changes).map(([key, ch]) => [key, ch ? { oldValue: ch.oldValue, newValue: ch.newValue } : undefined])
        ),
        timestamp: Date.now(),
      } as any;

      const isUrlScriptable = (url?: string): boolean => {
        if (!url) return false;
        const lower = url.toLowerCase();
        const restricted = [
          "chrome://",
          "chrome-extension://",
          "moz-extension://",
          "edge://",
          "about:",
          "file://",
          "data:",
        ];
        return !restricted.some((p) => lower.startsWith(p));
      };

      const isUrlSupportedByContent = (url?: string): boolean => {
        if (!url) return false;
        try {
          const host = new URL(url).hostname;
          return host.endsWith("xiaohongshu.com");
        } catch {
          return false;
        }
      };

      try {
        const tabs = await tabService.getAllTabs();
        await Promise.all(
          tabs.map(async (t: TabInfo) => {
            if (t.id && isUrlScriptable(t.url) && isUrlSupportedByContent(t.url)) {
              try {
                await MessageSender.sendToContent(t.id, payload);
              } catch {}
            }
          })
        );
      } catch {
        // 忽略广播失败
      }
    })();

    // 处理特定配置的变化
    handleStorageChanges(changes);
  });
}

/**
 * 处理存储变化
 */
function handleStorageChanges(changes: Record<string, Browser.storage.StorageChange>) {
  for (const [key, change] of Object.entries(changes)) {
    switch (key) {
      case STORAGE_KEYS.CONFIG:
        console.log("⚙️ Configuration updated");
        handleConfigurationChange(change);
        break;

      case STORAGE_KEYS.USER_DATA:
        console.log("👤 User data updated");
        handleUserDataChange(change);
        break;

      default:
        if (DEBUG) {
          console.log(`📝 Storage key '${key}' changed:`, {
            oldValue: change.oldValue,
            newValue: change.newValue,
          });
        }
    }
  }
}

/**
 * 处理配置变化
 */
function handleConfigurationChange(change: Browser.storage.StorageChange) {
  const oldConfig = change.oldValue;
  const newConfig = change.newValue;

  if (!oldConfig || !newConfig) return;

  // 检查主题变化
  if (oldConfig.theme !== newConfig.theme) {
    console.log(`🎨 Theme changed: ${oldConfig.theme} → ${newConfig.theme}`);
    // 可以通知所有 content script 更新主题
    broadcastThemeChange(newConfig.theme);
  }

  // 检查功能启用状态变化
  const oldFeatures = new Set(oldConfig.enabledFeatures || []);
  const newFeatures = new Set(newConfig.enabledFeatures || []);

  const added = [...newFeatures].filter((f) => !oldFeatures.has(f));
  const removed = [...oldFeatures].filter((f) => !newFeatures.has(f));

  if (added.length > 0) {
    console.log("🆕 Features enabled:", added);
  }

  if (removed.length > 0) {
    console.log("❌ Features disabled:", removed);
  }
}

/**
 * 处理用户数据变化
 */
function handleUserDataChange(change: Browser.storage.StorageChange) {
  if (DEBUG) {
    console.log("📈 User data statistics updated");
  }
}

/**
 * 广播主题变化
 */
async function broadcastThemeChange(theme: string) {
  try {
    await MessageSender.broadcastToContent({
      type: MessageType.INJECT_CSS,
      css: getThemeCSS(theme),
      id: "wxt-theme-style",
    });
  } catch (error) {
    console.error("Failed to broadcast theme change:", error);
  }
}

/**
 * 获取主题CSS
 */
function getThemeCSS(theme: string): string {
  switch (theme) {
    case "dark":
      return `
        #wxt-floating-button {
          background: #2d3748 !important;
          color: #f7fafc !important;
        }
        #wxt-extension-panel {
          background: #2d3748 !important;
          color: #f7fafc !important;
          border-color: #4a5568 !important;
        }
      `;
    case "light":
      return `
        #wxt-floating-button {
          background: #4CAF50 !important;
          color: white !important;
        }
        #wxt-extension-panel {
          background: white !important;
          color: #333 !important;
          border-color: #e0e0e0 !important;
        }
      `;
    default:
      return "";
  }
}

/**
 * 其他浏览器事件处理
 */
function setupBrowserEvents() {
  // 扩展启动事件
  if (browser.runtime.onStartup) {
    browser.runtime.onStartup.addListener(() => {
      console.log("🚀 Extension startup");
      // 可以在这里执行启动时的初始化工作
    });
  }

  // 扩展挂起事件
  if (browser.runtime.onSuspend) {
    browser.runtime.onSuspend.addListener(() => {
      console.log("🛑 Extension suspending...");
      // 清理资源、保存状态等
      performCleanupBeforeSuspend();
    });
  }

  // 扩展挂起取消事件
  if (browser.runtime.onSuspendCanceled) {
    browser.runtime.onSuspendCanceled.addListener(() => {
      console.log("🔄 Extension suspend canceled");
    });
  }

  // 通知点击事件
  if (browser.notifications?.onClicked) {
    browser.notifications.onClicked.addListener((notificationId) => {
      console.log("🔔 Notification clicked:", notificationId);
      handleNotificationClick(notificationId);
    });
  }

  // 通知关闭事件
  if (browser.notifications?.onClosed) {
    browser.notifications.onClosed.addListener((notificationId, byUser) => {
      if (DEBUG) {
        console.log("❌ Notification closed:", { notificationId, byUser });
      }
    });
  }

  // 窗口焦点变化事件
  if (browser.windows?.onFocusChanged) {
    browser.windows.onFocusChanged.addListener((windowId) => {
      if (windowId !== browser.windows.WINDOW_ID_NONE) {
        console.log("👁️ Window focused:", windowId);
      }
    });
  }
}

/**
 * 处理通知点击
 */
function handleNotificationClick(notificationId: string) {
  if (notificationId.startsWith("install-")) {
    // 安装通知被点击，可以打开帮助页面
    browser.tabs.create({ url: "https://wxt.dev/guide/" });
  } else if (notificationId.startsWith("update-")) {
    // 更新通知被点击，可以打开更新日志
    browser.tabs.create({ url: "https://github.com/your-org/your-extension/releases" });
  }
}

/**
 * 挂起前的清理工作
 */
function performCleanupBeforeSuspend() {
  // 清理内存中的缓存
  StorageService.getInstance().clearExpiredCache();

  // 保存重要状态
  // 这里可以添加需要在挂起前保存的重要数据

  console.log("🧹 Cleanup completed before suspend");
}
